package com.cskaoyan.service;


import com.cskaoyan.bean.Topic;
import com.cskaoyan.bean.TopicExample;
import com.cskaoyan.bean.vo.AdminAdForListDataBean;
import com.cskaoyan.mapper.TopicMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class AdminTopicServiceImp implements AdminTopicService {

    @Autowired
    TopicMapper topicMapper;

    @Override
    public AdminAdForListDataBean<Topic> queryTopics(Integer page, Integer limit, String title, String subtitle, String sort, String order) {
        PageHelper.startPage(page, limit);
        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria = topicExample.createCriteria();
        if (title != null && !"".equals(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (subtitle != null && !"".equals(subtitle)) {
            criteria.andSubtitleLike("%" + subtitle + "%");
        }
        criteria.andDeletedEqualTo(false);
        topicExample.setOrderByClause(sort + " " + order);
        List<Topic> topics = topicMapper.selectByExample(topicExample);
        long total = new PageInfo<>(topics).getTotal();
        return new AdminAdForListDataBean<Topic>(total, topics);
    }

    @Override
    public Integer addTopic(Topic topic) {
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        topic.setAddTime(dateTime);
        topic.setUpdateTime(dateTime);
        int result = topicMapper.insertSelective(topic);
        topic.setDeleted(null);
        topic.setSortOrder(null);
        return result;
    }

    @Override
    public Integer updateTopic(Topic topic) {
        int result = topicMapper.updateByPrimaryKeySelective(topic);
        return result;
    }

    /**
     * 因为是逻辑删除。。所以只需要更改对应的deleted参数。
     * @param topic
     * @return 如果返回值为1，则逻辑删除成功
     */
    @Override
    public Integer deleteTopic(Topic topic) {
        topic.setDeleted(true);
        return updateTopic(topic);
    }
}
